/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import me.zhengjie.exception.BizException;
import me.zhengjie.modules.shop.domain.ProductModule;
import me.zhengjie.modules.shop.domain.req.ProductModuleReq;
import me.zhengjie.modules.shop.domain.resp.ModuleContentResp;
import me.zhengjie.modules.shop.domain.resp.ProductModuleResp;
import me.zhengjie.modules.shop.domain.resp.ProductResp;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.shop.service.ProductModuleService;
import me.zhengjie.modules.shop.domain.vo.ProductModuleQueryCriteria;
import me.zhengjie.modules.shop.mapper.ProductModuleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.sql.Array;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.modules.biz.domain.enums.ErrorCode.TREE_LEVEL_EXCEED_MIX_SIZE;

/**
* @description 服务实现
* @author yiwei.he
* @date 2024-04-11
**/
@Service
@RequiredArgsConstructor
public class ProductModuleServiceImpl extends ServiceImpl<ProductModuleMapper, ProductModule> implements ProductModuleService {

    private final ProductModuleMapper productModuleMapper;

    @Override
    public PageResult<ProductModule> queryAll(ProductModuleQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(productModuleMapper.findAll(criteria, page));
    }

    @Override
    public List<ProductModule> queryAll(ProductModuleQueryCriteria criteria){
        return productModuleMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ProductModule resources) throws BizException {
        if(resources.getParentId() == null){
            resources.setParentId(0L);
        }
        Long parentId = resources.getParentId();
        // 顶级模块 或者 其父级为顶级模块
        if (parentId == 0 || parentIsTopLevel(parentId)) {
            save(resources);
        } else {
            throw new BizException(TREE_LEVEL_EXCEED_MIX_SIZE.getCode(), TREE_LEVEL_EXCEED_MIX_SIZE.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProductModule resources) {
        ProductModule productModule = getById(resources.getId());
        productModule.copy(resources);
        saveOrUpdate(productModule);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<ProductModuleResp> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProductModuleResp productModule : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分类名称", productModule.getType() == 1 ? "---" + productModule.getName() : "  " + productModule.getName());
            map.put("模块等级", productModule.getType() == 1 ? "顶级模块" : "子级模块");
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<ProductModule> moduleTree(ProductModuleReq req) {
        // 如果传入的父级为空 则默认为0
        if(req.getParentId() == null){
            req.setParentId(0L);
        }
        List<ProductModule> productModules = productModuleMapper.findAll(new ProductModuleQueryCriteria());
        //将所有的模块查询出来装到map中，相当于放在内存中，方便等会儿会通过id去取对象
        HashMap<Long, ProductModule> map = new HashMap<>();
        for(ProductModule productModule : productModules){
            map.put(productModule.getId(),productModule);
        }
        ArrayList<ProductModule> moduleTree = new ArrayList<>();
        for(ProductModule productModule : productModules){
            if(Objects.equals(productModule.getParentId(), req.getParentId())){
                moduleTree.add(productModule);
            }else {
                //获取父模块的ID
                Long parentId = productModule.getParentId();
                //获取父模块的对象
                ProductModule parentProductModule = map.get(parentId);
                if(parentProductModule != null){
                    //将自己装入到父类的children中
                    List<ProductModule> children = parentProductModule.getChildren();
                    children.add(productModule);
                }
            }
        }
        return moduleTree;
    }

    @Override
    public PageResult<ProductModuleResp> moduleSelect(Page<Object> page) {
        List<ProductModuleResp> list = getModuleList();
        return PageUtil.toPage(PageUtil.paging((int) page.getCurrent() - 1, (int) page.getSize(), list),list.size());
    }

    @Override
    public List<ProductModuleResp>  getModuleList() {
        ProductModuleReq req = new ProductModuleReq();
        req.setParentId(0L);
        List<ProductModule> moduleTree = this.moduleTree(req);
        // 前端只能接收这种格式，SB代码
        List<ProductModuleResp> list = new ArrayList<>();
        moduleTree.forEach(module -> {
            ProductModuleResp resp = new ProductModuleResp();
            BeanUtil.copyProperties(module, resp);
            resp.setType(1);
            list.add(resp);
            if (module.getChildren() != null && !module.getChildren().isEmpty()) {
                module.getChildren().forEach(child -> {
                    ProductModuleResp cresp = new ProductModuleResp();
                    BeanUtil.copyProperties(child, cresp);
                    cresp.setType(2);
                    list.add(cresp);
                });
            }
        });
        return list;
    }

    private boolean parentIsTopLevel(Long parentId) {
        ProductModule productModule = productModuleMapper.selectById(parentId);
        return productModule != null && productModule.getParentId() == 0;
    }
}